package sample.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import sample.dto.Child;
import sample.dto.Parent;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query;

@SuppressWarnings("serial")
public class LowLevelAPI implements Serializable{
	
	DatastoreService DatastoreService;
	
	//Create
	public void SaveParent(Parent ParentEntity){
		service();
		Entity RootEntity = new Entity(ParentEntity.getKey());
		RootEntity.setProperty("RootValue",ParentEntity.getValue());
		DatastoreService.put(RootEntity);
	}
	
	public void SaveChild(Child ChildEntity){
		service();
		Entity Entity = new Entity(ChildEntity.getChildKey());
		Entity.setProperty("EntityValue1",ChildEntity.getChildValue1());
		Entity.setProperty("EntityValue2",ChildEntity.getChildValue2());
		DatastoreService.put(Entity);
	}
	
	//Read
	public List<Parent> getParentList(){
		service();
		Query ParentQuery = new Query("Parent");
		Iterable<Entity> ParentIter = DatastoreService.prepare(ParentQuery).asIterable();
		ArrayList<Parent> ParentList= new ArrayList<Parent>();
		for (Entity ParentEntity : ParentIter) {			
			ParentList.add(new Parent(ParentEntity.getKey(),(String)ParentEntity.getProperty("RootValue")));
		}
		return ParentList;
	}
	
	public List<Child> getChildList(Key parentkey){
		service();
		ArrayList<Child> ChildList= new ArrayList<Child>();
		Query ChildQuery = new Query("Child",parentkey);
		Iterable<Entity> ChildIter = DatastoreService.prepare(ChildQuery).asIterable();
		for(Entity ChildEntity:ChildIter){
			ChildList.add(new Child(ChildEntity.getKey(),(String)ChildEntity.getProperty("EntityValue1"),(String)ChildEntity.getProperty("EntityValue2")));
		}
		return ChildList;
	}
	
	//UpDate
	public void UpDateParent(Parent ParentEntity){
		service();
		try{
			Entity RootEntity = DatastoreService.get(ParentEntity.getKey());
			RootEntity.setProperty("RootValue",ParentEntity.getValue());
			DatastoreService.put(RootEntity);
		}catch (EntityNotFoundException e) {
			
			System.out.println("要素がありません");
		}
	}
	
	public void UpDateChild(Child ChildEntity){
		service();
		try{
			Entity Entity = DatastoreService.get(ChildEntity.getChildKey());
			Entity.setProperty("EntityValue1",ChildEntity.getChildValue1());
			Entity.setProperty("EntityValue2",ChildEntity.getChildValue2());
			DatastoreService.put(Entity);

		}catch (EntityNotFoundException e) {
			
			System.out.println("要素がありません");
		}
	}
	
	//Delete
	public void DeleteEntity(Key Key){
		service();
		DatastoreService.delete(Key);
	}
	
	protected void service(){
		if(DatastoreService == null){
			DatastoreService = DatastoreServiceFactory.getDatastoreService();
		}
	}
}
